<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Enums\CheckStatusEnum;
use App\Enums\UserIdentityEnum;
use App\Exceptions\ApiException;
use App\Format\PassCardFormat;
use App\Models\PassCard;
use App\Models\UserProfile;

class PassCardService
{
    public function getList(int $page, int $pageSize, array $search)
    {
        $builder = PassCard::query()->with([
            'user:id',
            'user.userProfile:id,name,now_address,user_id,sex,phone,identity,id_card_number',
            'user.userProfile.houseBind:id,id_card_number,house_id',
            'user.userProfile.houseBind.house:id,houser_user_id',
            'user.userProfile.houseBind.house.houser:id,user_id,phone',
            'user.userProfile.check:user_id,check_status',
        ]);

        if (isset($search['check_status'])) {
            $builder->where('check_status', $search['check_status']);
        }

        if (isset($search['name'])) {
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('name', 'like', '%' . $search['name'] . '%');
            });
        }

        if (isset($search['now_address'])) {
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('now_address', 'like', '%' . $search['now_address'] . '%');
            });
        }

        if (isset($search['area'])) {
            // TODO check_status 是出入证的审核状态 不是用户的
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('area', $search['area']);
            });
        }

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function detail(int $id)
    {
        return PassCard::query()->with([
            'user:id',
            'user.userProfile:id,name,now_address,user_id,sex,phone,identity,id_card_number',
            'user.userProfile.houseBind:id,id_card_number,house_id',
            'user.userProfile.houseBind.house:id,houser_user_id',
            'user.userProfile.houseBind.house.houser:id,user_id,phone',
        ])->where('id', $id)->first();
    }

    public function delete(int $id)
    {
        $passCard = PassCard::query()->find($id);
        if (empty($passCard)) {
            throw new ApiException('数据不存在', 1);
        }
        $passCard->delete();
        return true;
    }

    public function createPassCardFromAdmin(PassCardFormat $passCardFormat, string $idCardNum, string $identity, int $status)
    {
        /** @var null|UserProfile $userProfile */
        $userProfile = UserProfile::query()
            ->select('user_id', 'id_card_number', 'id')
            ->where('id_card_number', $idCardNum)->first();
        if (empty($userProfile)) {
            throw new ApiException('无身份信息，请先录入人员', 1);
        }
        $passCardInfo = PassCard::query()
            ->select('id')
            ->where('user_id', $userProfile->user_id)->first();
        if (! empty($passCardInfo) && $status == CheckStatusEnum::CHECK_ING) {
            //新增出入证检查是否存在数据
            throw new ApiException('该人员已录入', 1);
        }
        if ($identity == UserIdentityEnum::FLOW_USER && empty($passCardFormat->getFlowRegisterCode())) {
            throw new ApiException('流动人口需要填写流管编码', 1);
        }
        if ($status == 3 && empty($passCardFormat->getPassCardPhoto())) {
            throw new ApiException('请上传出入证', 1);
        }
        $passCardFormat->setUserId($userProfile->user_id);
        $passCardFormat->setCheckStatus($status);
        $passCard = PassCard::query()->updateOrCreate([
            'user_id' => $passCardFormat->getUserId(),
        ], $passCardFormat->toArrayNotNull());

        $word = ($status == CheckStatusEnum::CHECK_ING ? '创建出入证' : '保存出入证草稿');
        adminLog($passCard, AdminActionTypeEnum::CREATE, $word);
        return true;
    }

    public function getExportData(array $search)
    {
        $builder = PassCard::query()
            ->with([
                'user:id',
                'user.userProfile:id,name,now_address,user_id,sex,phone,identity,id_card_number',
            ]);

        if (isset($search['check_status'])) {
            $builder->where('check_status', $search['check_status']);
        }
        if (isset($search['name'])) {
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('name', 'like', '%' . $search['name'] . '%');
            });
        }
        if (isset($search['now_address'])) {
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('now_address', 'like', '%' . $search['now_address'] . '%');
            });
        }
        if (isset($search['area'])) {
            $builder->whereHas('user.userProfile', function ($builder) use ($search) {
                $builder->where('area', $search['area']);
            });
        }
        if (isset($search['ids'])) {
            $builder->whereIn('id', $search['ids']);
        }

        $list = $builder->get();
        adminLog(new PassCard(), AdminActionTypeEnum::SELECT, '导出出入证数据');
        return $list;
    }
}
